#ifndef LINE_H
#define LINE_H

#include <WProgram.h>
#include <inttypes.h>

#define ID_ADC_LINE  	2
#define ID_LEFTRIGHT    12
#define ID_FRONTREAR    13
#define ID_DIRECTION_R   7
#define ID_DIRECTION_L   8


// line detect
#define NO_LINE    0
#define LEFT_LINE  1
#define RIGHT_LINE 2
#define FRONT_LINE 3


class Line
{
public:
	Line();
	int detect();
private:
	int _minDiff;
	int _grayValue;
	int _blackValue;
	int _whiteValue;
}

Line::Line()
{	
	pinMode(ID_LEFTRIGHT, OUTPUT);
	digitalWrite(ID_LEFTRIGHT, HIGH);

	pinMode(ID_FRONTREAR, OUTPUT);
	digitalWrite(ID_FRONTREAR, HIGH);

	/*
	 * These two should not be necessary, but are.
	 * If they are left out the light sensor readings
	 * are incorrect.
	 */
	pinMode(ID_DIRECTION_R, OUTPUT);
	digitalWrite(ID_DIRECTION_R, HIGH);

	pinMode(ID_DIRECTION_L, OUTPUT);
	digitalWrite(ID_DIRECTION_L, HIGH);
	
	_blackValue = 110;
	_whiteValue = 600;
	
	_minDiff = 50;
	_greyValue= _minDiff +(_whiteValue+_blackValue)/4;
}

Line::detect()
{
  int diff;
  int lineLeft, lineRight;
   /* Select ADC_LINE LEFT */
  digitalWrite(ID_FRONTREAR, LOW);
  digitalWrite(ID_LEFTRIGHT, LOW);
  delay(1); /* Give ADC time to sample */
  lineLeft = analogRead(ID_ADC_LINE);

  /* Select ADC_LINE RIGHT */
  digitalWrite(ID_FRONTREAR, LOW);
  digitalWrite(ID_LEFTRIGHT, HIGH);
  delay(1); /* Give ADC time to sample */
  lineRight = analogRead(ID_ADC_LINE);
  
  diff=lineLeft-lineRight;
  if(lineLeft>_greyValue && lineRight>_greyValue)
    return FRONT_LINE;
  else if(diff> _minDiff)
    return LEFT_LINE;
  else if(diff< -_minDiff)
    return RIGHT_LINE;
  else if(lineLeft<_greyValue && lineRight<_greyValue)
    return NO_LINE;
  else
    return FRONT_LINE;

}

#endif
